<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps,VbenFormProps } from '#/adapter';

import { ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter';
import {list,destroy,execute,pause,resume} from '#/api/monitor/crontab';
import { Icon } from '#/components/icon';
import { TableAction } from '#/components/table-action';

import CrontabForm from './form.vue';
import CrontabLogsWrap from './logs-wrap.vue';

import {gridSchemas, searchFormSchemas } from './schemas';


const hasTopTableDropDownActions = ref(false);
const crontabFormRef = ref();
const crontabLogsWrapRef=ref();

const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
};

const gridOptions: VxeGridProps<any> = {
  ...gridSchemas,
  toolbarConfig: {
    ...gridSchemas.toolbarConfig,
    slots: {
      buttons: 'toolbar-buttons',
    },
    custom: {
      // 自定义列-图标
      icon: 'vxe-icon-menu',
    },
  },
  // border: false,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await list({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};



const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

// 打开新增表单
const handleAdd = () => {
  console.log(crontabFormRef.value)
  crontabFormRef.value.setData({
    isUpdate: false,
    gridApi,
  });
  crontabFormRef.value.open();
};

// 打开编辑表单
const handleEdit = (record: any) => {
  crontabFormRef.value.setData({
    record,
    isUpdate: true,
    gridApi,
  });
  crontabFormRef.value.open();
};

//恢复任务
const handleResume = (row: any) => {

  let data = [];
  if (row) {
    data.push(row.id);
  } else {
    data = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  resume({data}).then(() => {
    message.success('恢复成功');
    gridApi.reload();
  });

};

/**
 * 暂停任务
 * @param row
 */
const handlePause = (row: any) => {
  let data = [];
  if (row) {
    data.push(row.id);
  } else {
    data = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  pause({data}).then(() => {
    message.success('执行成功');
    gridApi.reload();
  });

};

/**
 * 执行任务
 * @param row
 */
const handleExecute = (row: any) => {
  let data = [];
  if (row) {
    data.push(row.id);
  } else {
    data = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  execute({data}).then(() => {
    message.success('执行成功');
    gridApi.reload();
  });

};

// 删除
const handleDelete = (row: any) => {
  let data = [];
  if (row) {
    data.push(row.id);
  } else {
    data = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  destroy(0,{data}).then(() => {
    message.success('删除成功');
    gridApi.reload();
  });
};

/**
 * 任务日志
 * @param record
 */
const handleCrontabLogs = (record: any) => {
  crontabLogsWrapRef.value.setData({
    record,
  });
  crontabLogsWrapRef.value.open();
};

</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              auth: ['admin', 'monitor:crontab:save'],
              onClick: handleAdd.bind(null),
            }]"
          :drop-down-actions="[{
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              auth: ['admin', 'monitor:crontab:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, false),
              },
            },]"
        >
          <template #more>
            <Button style="margin-left: 8px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row }">
        <TableAction
        :actions="[
            {
              label: '执行',
              type: 'link',
              size: 'small',
              auth: ['admin', 'monitor:crontab:detail'],
              popConfirm: {
                title: '确定执行该任务？',
                confirm: handleExecute.bind(null, row),
              },
            },
            {
              label: '编辑',
              type: 'link',
              size: 'small',
              auth: ['admin', 'monitor:crontab:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: '日志',
              type: 'link',
              size: 'small',
              auth: ['admin', 'monitor:crontab:logs'],
              onClick: handleCrontabLogs.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: '启动',
              type: 'link',
              size: 'small',
              icon: 'ant-design:play-circle-outlined',
              auth: ['admin', 'monitor:crontab:resume'],
              ifShow() {
                return (row.enabled === 0);
              },
              popConfirm: {
                title: '确定启动该任务？',
                confirm: handleResume.bind(null, row),
              },
            },
            {
              label: '停止',
              type: 'link',
              size: 'small',
              icon: 'ant-design:pause-outlined',
              auth: ['admin', 'monitor:crontab:pause'],
              ifShow() {
                return (row.enabled === 1);
              },
              popConfirm: {
                title: '确定停止该任务？',
                confirm: handlePause.bind(null, row),
              },
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              auth: ['admin', 'monitor:crontab:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
    <CrontabForm ref="crontabFormRef" />
    <CrontabLogsWrap ref="crontabLogsWrapRef" />
  </Page>
</template>
